<template>
  <div class="app-container">
    <el-table v-loading="loading" :data="tableList" border style="margin-bottom: 30px"
      v-if="this.$route.query.type === 'equipment'">
      <el-table-column label="设备名称" align="center" prop="nickName" />
      <el-table-column label="蓝牙mac地址" align="center" prop="deviceId" />
      <el-table-column label="型号" align="center" prop="equipmentModel" />
      <el-table-column label="使用人" align="center" prop="yhMinUser.uname" />
      <el-table-column label="电话" align="center" prop="yhMinUser.uphone" />
      <el-table-column label="绑定时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleClickDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-loading="loading" :data="userarr" border style="margin-bottom: 30px"
      v-if="this.$route.query.type === 'user'">
      <el-table-column label="姓名" align="center" prop="uname" />
      <el-table-column label="电话" align="center" prop="uphone" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="身高(cm)" align="center" prop="height" />
      <el-table-column label="体重(kg)" align="center" prop="weight" />
      <el-table-column label="药物类型" align="center" prop="drugCategoryName" />
      <el-table-column label="最近服用药" align="center" prop="recentMedication" />
      <el-table-column label="服用频率" align="center" prop="drugFrequencyName" />
      <!-- <el-table-column label="绑定设备" align="center" prop="createTime" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleClickDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px" v-if="this.$route.query.type === 'user'">
      设备名称
      <el-select v-model="seleceVal" placeholder="请选择" @change="handleChangeEquipment">
        <el-option v-for="item in equipmentList" :key="item.value" :label="item.nickName" :value="item.deviceId">
        </el-option>
      </el-select>
    </div>
    <el-row :gutter="50">
      <el-col :span="8">
        <Data @changeType="handleChangeTab" chartsType="step" ref="step" :info="stepOption" :progress="step"
          :deviceId="equipmentInfo.deviceId" :alertNum="sleepNum"></Data>
      </el-col>
      <el-col :span="8">
        <Data @changeType="handleChangeTab" :info="xinlvOption" :progress="xinlv" ref="xinlv" chartsType="xinlv"
          :deviceId="equipmentInfo.deviceId" :alertNum="bloodPressureNum"></Data>
      </el-col>
      <el-col :span="8">
        <Data @changeType="handleChangeTab" :info="pressureOption" chartsType="pressure" ref="pressure"
          :progress="pressure" :deviceId="equipmentInfo.deviceId" :alertNum="bloodOxygenNum"></Data>
      </el-col>
      <el-col :span="8">
        <Data @changeType="handleChangeTab" :info="bloodOption" ref="blood" chartsType="blood"
          :deviceId="equipmentInfo.deviceId" :progress="blood" :alertNum="numStepNum"></Data>
      </el-col>
      <el-col :span="8">
        <Data @changeType="handleChangeTab" chartsType="sleep" ref="sleep" :info="sleepOption" :progress="shuimian"
          :deviceId="equipmentInfo.deviceId" :alertNum="heartRateNum"></Data>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import Data from "./modules/data.vue";
  import echarts from "echarts";
  import {
    getEquipment
  } from "@/api/system/equipment";
  import {
    getMiniuser
  } from "@/api/system/miniuser";

  import {
    getHeartRate,
    getStepCount,
    getBloodOxygen,
    getBloodPressure,
    getSleepGroupList,
    getListByPhone,
    getNum
  } from "@/api/motion";
  import {
    getWeekList
  } from "@/utils/ruoyi";

  export default {
    data() {
      return {
        tableList: [],
        loading: false,
        xinlvOption: {},
        stepOption: {},
        bloodOption: {},
        pressureOption: {},
        sleepOption: {},
        step: {},
        shuimian: {
          min: 0,
          max: 16,
          list: [6, 1.4, 0.1, 1.5, 7],
          interval: 16,
        },
        xinlvAll: {
          youth: {
            min: 70,
            max: 150,
            list: [10, 20, 20, 20, 10],
            interval: 80,
          },
          adult: {
            min: 50,
            max: 110,
            list: [20, 10, 10, 10, 10],
            interval: 60,
          },
          old: {
            min: 40,
            max: 100,
            list: [20, 10, 10, 10, 10],
            interval: 60,
          },
        },
        xinlv: {},
        pressure: {},
        blood: {
          min: 70,
          max: 100,
          list: [15, 5, 4, 2, 4],
          interval: 30,
        },
        timeType: "day",
        equipmentInfo: {},
        userarr: [],
        seleceVal: '',
        equipmentList: [],
        alertList: ['sleep', 'heartRate', 'bloodPressure', 'bloodOxygen', 'numStep'],
        sleepNum: 0,
        bloodPressureNum: 0,
        bloodOxygenNum: 0,
        numStepNum: 0,
        heartRateNum: 0,
      };
    },
    components: {
      Data,
    },
    created() {},
    mounted() {
      if (this.$route.query.type === "user") {
        this.getUserInfo();
      } else {
        this.getInfo();
      }
      console.log(this.parseTime("2022-05-18", "{d}"));
      // this.$refs.sleep.init();
    },
    methods: {
      handleChangeEquipment(val) {
        console.log(val)
        this.equipmentInfo.deviceId = val
        this.init()
      },
      getEquipmentList(phone) {
        getListByPhone({
          phone
        }).then(res => {
          if (res.code === 200) {
            if (res.data.length > 0) {
              this.seleceVal = res.data[0].deviceId
              this.equipmentList = res.data
              this.equipmentInfo.deviceId = this.seleceVal
              this.init()
            }
          }
        })
      },
      getUserInfo() {
        getMiniuser({
          id: this.$route.query.id,
        }).then((response) => {
          this.equipmentInfo = response.data[0];
          this.userarr = response.data;
          this.setData(this.equipmentInfo, true);
          this.getEquipmentList(this.equipmentInfo.uphone)
        });
      },
      getCurrentWeek() {
        let week = getWeekList(new Date(), "current", "-");
        let weekInfo = {};
        week.forEach((item) => {
          weekInfo[item] = 0;
        });
      },
      // 步数
      getStepCount() {
        getStepCount({
          type: this.timeType,
          deviceId: this.equipmentInfo.deviceId,
        }).then((res) => {
          const data = res.data.data;
          const userInfo = this.equipmentInfo.yhMinUser || this.equipmentInfo;
          const distance = this.getStepDistance(userInfo.sex, userInfo.height);
          data.km = ((data.step * distance) / 1000).toFixed(1);
          const step = {
            min: 0,
            max: 3600,
            interval: 3600,
            list: [2399, 600, 1, 600],
          };
          if (data.step > 3600) {
            step.max = 3600 + data.step;
            step.interval = step.max - step.min;
            step.list.push(step.interval - 3600);
          }
          this.step = step;
          let xAxis = [];
          let series = [];
          res.data.list.forEach((item) => {
            if (this.timeType === "day") {
              xAxis.push(item.newTime.split(" ")[1] + ":00");
            } else {
              xAxis.push(item.newTime);
            }
            series.push(item.step);
          });
          const length = xAxis.length;
          this.stepOption = {
            detail: data,
            option: {
              tooltip: {
                trigger: "axis",
              },
              xAxis: {
                type: "category",
                data: xAxis,
              },
              yAxis: {
                type: "value",
              },
              dataZoom: [{
                  type: "slider",
                  realtime: true,
                  start: 0,
                  end: Math.floor(100 / (length / 7)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
                  height: 5, //组件高度
                  left: 5, //左边的距离
                  right: 5, //右边的距离
                  bottom: 10, //下边的距离
                  show: length > 7, // 是否展示
                  fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
                  borderColor: "rgba(17, 100, 210, 0.12)",
                  handleSize: 0, //两边手柄尺寸
                  showDetail: false, //拖拽时是否展示滚动条两侧的文字
                  zoomLock: true, //是否只平移不缩放
                  moveOnMouseMove: false, //鼠标移动能触发数据窗口平移
                  //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
                },
                {
                  type: "inside", // 支持内部鼠标滚动平移
                  start: 0,
                  end: Math.floor(100 / (length / 7)),
                  zoomOnMouseWheel: false, // 关闭滚轮缩放
                  moveOnMouseWheel: true, // 开启滚轮平移
                  moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
                },
              ],
              series: [{
                data: series,
                type: "line",
                color: "rgba(91,143,249,1)",
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: "rgba(58,77,233,0.2)",
                    },
                    {
                      offset: 1,
                      color: "rgba(58,77,233,0)",
                    },
                  ]),
                },
                smooth: true,
              }, ],
            },
          };
          this.$nextTick(() => {
            this.$refs.step.init();
          });
        });
      },
      // 睡眠
      getSleepGroupList() {
        getSleepGroupList({
          type: this.timeType,
          deviceId: this.equipmentInfo.deviceId,
        }).then((res) => {
          const data = res.data.data;
          var hour = parseInt((Number(data.sleepminute)) / 60)
          var minute = parseInt((Number(data.sleepminute)) % 60)
          data.hour = hour;
          data.minute = minute;
          let xAxis = [];
          let series1 = [];
          let series2 = [];

          res.data.list.forEach((item) => {
            xAxis.push(item.newTime);
            series1.push(Math.abs(Number(item.deepAll) / 60).toFixed(2));
            series2.push(Math.abs(Number(item.shallowAll) / 60).toFixed(2));
          });
          const length = xAxis.length;
          this.sleepOption = {
            option: {
              tooltip: {
                trigger: "axis",
                axisPointer: {
                  type: "shadow",
                },
              },
              legend: {
                right: 0,
              },
              grid: {
                left: "3%",
                right: "4%",
                bottom: "3%",
                containLabel: true,
              },
              xAxis: {
                type: "category",
                data: xAxis,
              },
              yAxis: {
                type: "value",
                name: "小时",
                max: 24,
                minInterval: 1,
              },
              dataZoom: [{
                  type: "slider",
                  realtime: true,
                  start: 0,
                  end: Math.floor(100 / (length / 7)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
                  height: 5, //组件高度
                  left: 5, //左边的距离
                  right: 5, //右边的距离
                  bottom: 10, //下边的距离
                  show: length > 7, // 是否展示
                  fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
                  borderColor: "rgba(17, 100, 210, 0.12)",
                  handleSize: 0, //两边手柄尺寸
                  showDetail: false, //拖拽时是否展示滚动条两侧的文字
                  zoomLock: true, //是否只平移不缩放
                  moveOnMouseMove: false, //鼠标移动能触发数据窗口平移
                  //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
                },
                {
                  type: "inside", // 支持内部鼠标滚动平移
                  start: 0,
                  end: Math.floor(100 / (length / 7)),
                  zoomOnMouseWheel: false, // 关闭滚轮缩放
                  moveOnMouseWheel: true, // 开启滚轮平移
                  moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
                },
              ],
              series: [{
                  name: "深睡",
                  type: "bar",
                  stack: "total",
                  color: "rgba(129,211,248,1)",
                  data: series1,
                  barWidth: 30,
                },
                {
                  name: "浅睡",
                  type: "bar",
                  stack: "total",
                  color: "rgba(128,248,254,1)",
                  data: series2,
                  barWidth: 30,
                },
              ],
            },
            detail: data,
          };
          this.$nextTick(() => {
            this.$refs.sleep.init();
          });
        });
      },
      // 心率
      getHeartRate() {
        getHeartRate({
          type: this.timeType,
          deviceId: this.equipmentInfo.deviceId,
        }).then((res) => {
          let xAxis = [];
          let series = [];
          res.data.list.forEach((item) => {
            if (this.timeType === "day") {
              xAxis.push(item.newTime.split(" ")[1] + ":00");
            } else {
              xAxis.push(item.newTime);
            }
            series.push(item.xinlv);
          });
          const length = xAxis.length;
          this.xinlvOption = {
            detail: res.data.data,
            option: {
              xAxis: {
                type: "category",
                data: xAxis,
              },
              dataZoom: [{
                  type: "slider",
                  realtime: true,
                  start: 0,
                  end: Math.floor(100 / (length / 7)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
                  height: 5, //组件高度
                  left: 5, //左边的距离
                  right: 5, //右边的距离
                  bottom: 10, //下边的距离
                  show: length > 7, // 是否展示
                  fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
                  borderColor: "rgba(17, 100, 210, 0.12)",
                  handleSize: 0, //两边手柄尺寸
                  showDetail: false, //拖拽时是否展示滚动条两侧的文字
                  zoomLock: true, //是否只平移不缩放
                  moveOnMouseMove: false, //鼠标移动能触发数据窗口平移
                  //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
                },
                {
                  type: "inside", // 支持内部鼠标滚动平移
                  start: 0,
                  end: Math.floor(100 / (length / 7)),
                  zoomOnMouseWheel: false, // 关闭滚轮缩放
                  moveOnMouseWheel: true, // 开启滚轮平移
                  moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
                },
              ],
              yAxis: {
                type: "value",
              },
              series: [{
                data: series,
                type: "line",
                color: "rgba(91,143,249,1)",
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: "rgba(58,77,233,0.2)",
                    },
                    {
                      offset: 1,
                      color: "rgba(58,77,233,0)",
                    },
                  ]),
                },
              }, ],
            },
          };
          this.$nextTick(() => {
            this.$refs.xinlv.init();
          });
        });
      },
      // 血压
      getBloodPressure() {
        getBloodPressure({
          type: this.timeType,
          deviceId: this.equipmentInfo.deviceId,
        }).then((res) => {
          let xAxis = [];
          let series = [];
          let series2 = [];
          res.data.list.forEach((item) => {
            xAxis.push(item.newTime);
            series.push(item.shousuoya);
            series2.push(item.shuzhangya);
          });
          const length = xAxis.length;
          this.pressureOption = {
            detail: res.data.data,
            option: {
              xAxis: {
                type: "category",
                data: xAxis,
              },
              yAxis: {
                type: "value",
              },
              dataZoom: [{
                  type: "slider",
                  realtime: true,
                  start: 0,
                  end: Math.floor(100 / (length / 7)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
                  height: 5, //组件高度
                  left: 5, //左边的距离
                  right: 5, //右边的距离
                  bottom: 10, //下边的距离
                  show: length > 7, // 是否展示
                  fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
                  borderColor: "rgba(17, 100, 210, 0.12)",
                  handleSize: 0, //两边手柄尺寸
                  showDetail: false, //拖拽时是否展示滚动条两侧的文字
                  zoomLock: true, //是否只平移不缩放
                  moveOnMouseMove: false, //鼠标移动能触发数据窗口平移
                  //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
                },
                {
                  type: "inside", // 支持内部鼠标滚动平移
                  start: 0,
                  end: Math.floor(100 / (length / 7)),
                  zoomOnMouseWheel: false, // 关闭滚轮缩放
                  moveOnMouseWheel: true, // 开启滚轮平移
                  moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
                },
              ],
              series: [{
                  data: series,
                  name: "收缩压",
                  type: "line",
                  color: "rgba(91,143,249,1)",
                  areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: "rgba(58,77,233,0.2)",
                      },
                      {
                        offset: 1,
                        color: "rgba(58,77,233,0)",
                      },
                    ]),
                  },
                  smooth: true,
                },
                {
                  data: series2,
                  name: "舒张压",
                  type: "line",
                  color: "rgba(236,128,141,1)",
                  areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: "rgba(58,77,233,0.2)",
                      },
                      {
                        offset: 1,
                        color: "rgba(58,77,233,0)",
                      },
                    ]),
                  },
                  smooth: true,
                },
              ],
            },
          };
          this.$nextTick(() => {
            this.$refs.pressure.init();
          });
        });
      },
      // 血氧
      getBloodOxygen() {
        getBloodOxygen({
          type: this.timeType,
          deviceId: this.equipmentInfo.deviceId,
        }).then((res) => {
          let xAxis = [];
          let series = [];
          res.data.list.forEach((item) => {
            xAxis.push(item.newTime);
            series.push(item.xueyang);
          });
          const length = xAxis.length;
          this.bloodOption = {
            detail: res.data.data,
            option: {
              xAxis: {
                type: "category",
                data: xAxis,
              },
              yAxis: {
                type: "value",
              },
              dataZoom: [{
                  type: "slider",
                  realtime: true,
                  start: 0,
                  end: Math.floor(100 / (length / 7)), // 数据窗口范围的结束百分比。范围是：0 ~ 100。
                  height: 5, //组件高度
                  left: 5, //左边的距离
                  right: 5, //右边的距离
                  bottom: 10, //下边的距离
                  show: length > 7, // 是否展示
                  fillerColor: "rgba(17, 100, 210, 0.42)", // 滚动条颜色
                  borderColor: "rgba(17, 100, 210, 0.12)",
                  handleSize: 0, //两边手柄尺寸
                  showDetail: false, //拖拽时是否展示滚动条两侧的文字
                  zoomLock: true, //是否只平移不缩放
                  moveOnMouseMove: false, //鼠标移动能触发数据窗口平移
                  //zoomOnMouseWheel: false, //鼠标移动能触发数据窗口缩放
                },
                {
                  type: "inside", // 支持内部鼠标滚动平移
                  start: 0,
                  end: Math.floor(100 / (length / 7)),
                  zoomOnMouseWheel: false, // 关闭滚轮缩放
                  moveOnMouseWheel: true, // 开启滚轮平移
                  moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
                },
              ],
              series: [{
                data: series,
                type: "line",
                color: "rgba(91,143,249,1)",
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: "rgba(58,77,233,0.2)",
                    },
                    {
                      offset: 1,
                      color: "rgba(58,77,233,0)",
                    },
                  ]),
                },
                smooth: true,
              }, ],
            },
          };
          this.$nextTick(() => {
            this.$refs.blood.init();
          });
        });
      },
      handleClickDetail(row) {
        if (this.$route.query.type === "user") {
          this.$router.push({
            path: "/userdet",
            query: {
              id: row.id,
              uphone: row.uphone,
            },
          });
        } else {
          this.$router.push({
            path: "/equipmentDetails",
            query: {
              id: row.id,
              delFlag: row.delFlag,
            },
          });
        }
      },
      handleChangeTab(info) {
        console.log(info);
        this.timeType = info.val;
        if (info.type === "xinlv") {
          this.getHeartRate();
        }
        if (info.type === "step") {
          this.getStepCount();
        }
        if (info.type === "sleep") {
          this.getSleepGroupList();
        }
        if (info.type === "pressure") {
          this.getBloodPressure();
        }
        if (info.type === "blood") {
          this.getBloodOxygen();
        }
      },
      getInfo() {
        getEquipment(this.$route.query.id).then((response) => {
          if (response.code === 200) {
            this.equipmentInfo = response.data;
            this.tableList.push(response.data);
            const userInfo = response.data.yhMinUser;
            this.setData(userInfo);
          }
        });
      },
      setData(userInfo, type) {
        let shuzhangya = {};
        let shousuoya = {};
        if (userInfo.age < 22) {
          this.xinlv = this.xinlvAll.youth;
        }
        if ((userInfo.age >= 22) & (userInfo.age <= 59)) {
          this.xinlv = this.xinlvAll.adult;
        }
        if (userInfo.age >= 60) {
          this.xinlv = this.xinlvAll.old;
        }
        if (userInfo.age < 35) {
          shuzhangya = {
            min: 70,
            max: 200,
            interval: 130,
            list: [33, 11, 1, 12, 73],
          };
          shousuoya = {
            min: 50,
            max: 100,
            interval: 50,
            list: [17, 7, 1, 8, 17],
          };
        }
        if (userInfo.age > 35 && userInfo.age < 50) {
          shuzhangya = {
            min: 70,
            max: 200,
            interval: 130,
            list: [42, 12, 1, 13, 62],
          };
          shousuoya = {
            min: 50,
            max: 100,
            interval: 50,
            list: [21, 8, 1, 8, 12],
          };
        }
        if (userInfo.age > 50 && userInfo.age < 60) {
          shuzhangya = {
            min: 70,
            max: 200,
            interval: 130,
            list: [54, 14, 1, 14, 47],
          };
          shousuoya = {
            min: 50,
            max: 110,
            interval: 60,
            list: [26, 8, 1, 9, 16],
          };
        }
        if (userInfo.age > 60) {
          shuzhangya = {
            min: 70,
            max: 200,
            interval: 130,
            list: [64, 15, 1, 15, 35],
          };
          shousuoya = {
            min: 50,
            max: 110,
            interval: 60,
            list: [20, 18, 2, 9, 11],
          };
        }
        this.$set(this.pressure, "shousuoya", shousuoya);
        this.$set(this.pressure, "shuzhangya", shuzhangya);
        if (type) return
        this.init();
      },
      init() {
        this.getHeartRate();
        this.getStepCount();
        this.getBloodOxygen();
        this.getBloodPressure();
        this.getSleepGroupList();
        this.getAlertNum()
      },
      getAlertNum() {
        this.alertList.forEach(item => {
          getNum({
            prewarnHealthDeviceUserid: this.equipmentInfo.uphone,
            prewarnHealthType: item
          }).then(res => {
            if (res.code === 200) {
              this[item + 'Num'] = res.total;
            }
          })
        })
      },
      getStepDistance(gender, height) {
        if (height == 0 || !height) {
          return 70 / 100;
        }
        if (gender == "1") {
          return (height * 0.415) / 100;
        } else {
          return (height * 0.413) / 100;
        }
      },
    },
  };
</script>
<style lang="scss" scoped>
</style>
